<!-- 蓝色简洁登录页面 -->
<template>
	<view class="t-login">
		<!-- 页面装饰图片 -->
		<div class="bgImgs">
			<img class="banner one" src="../../static/di tu yi/ditu_zuo.jpeg" alt="">
			<img class="banner two" src="../../static/di tu yi/ditu_youshang.jpeg" alt="">
			<img class="banner three" src="../../static/di tu yi/ditu_zuoxia.jpeg" alt="">
			<img class="banner fore" src="../../static/di tu yi/ditu_youxia.jpeg" alt="">
		</div>
		<!-- 标题 -->
		<view class="t-b">{{ title }}</view>
		<view class="t-b2">{{ subTitle }}</view>
		<form class="cl">
			<!-- 登录账号 -->
			<!-- <view class="login-form-item">
				<u-input v-model="username" placeholder="请输入登录用户名" maxlength="30">
					<u-icon slot="prefix" name="account" size="35px"></u-icon>
				</u-input>
			</view> -->
			<!-- 登录密码 -->
			<!-- <view class="login-form-item">
				<u-input v-model="password" type="password" placeholder="请输入登录密码" maxlength="16">
					<u-icon slot="prefix" name="lock" size="35px"></u-icon>
				</u-input>
			</view> -->
			<!-- 图形验证码 -->
			<!-- <view class="login-form-item t-captcha">
				<u-input v-model="captchaCode" type="number" placeholder="请输入验证码" maxlength="4">
					<u-icon slot="prefix" name="fingerprint" size="35px"></u-icon>
				</u-input>
				<image :src="captcha" @click="getCaptcha" class="t-captcha-img"></image>
			</view> -->
			<button @tap="login()">一 键 登 录</button>
		</form>
	</view>
</template>
<script>
import {getQueryString} from '@/utils/index.js'
import {login, getInfo} from "@/api/user";
export default {
	data() {
		return {
			token: uni.getStorageSync('AccessToken') || '',
			title: 'AI智能人岗匹配系统',
			subTitle: '欢迎使用！',
			// 图形验证码信息
			captcha: null,
			// 登录账号
			username: 'admin',
			// 密码
			password: 'admin123',
			// 图形验证码
			captchaCode: '',
			uuid: '',
			appid: 'wx1f2b7a6d50d0f9d6',
      redirect_uri: 'https://yanj.com.cn/pages/login/index',
		};
	},
	created() {
		const token = uni.getStorageSync('AccessToken') || ''
		if (token) {
			this.getuserInfo();
			return uni.reLaunch({
				url: '/pages/index/index'   //  bushu
			})
		}
		this.$nextTick(async () => {
			const code = await this.getQueryString('code') || null;
			// 判断有没有存储 sessionKey
			let sessionKey = localStorage.getItem("sessionKey") || null;
			if (!sessionKey) {
				sessionKey = this.generateSessionKey(16);
				localStorage.setItem("sessionKey", sessionKey);
			}
			if (code) {
				uni.setStorageSync('AccessToken', '')
				this.getToken(code, sessionKey)
			}
		})
	},
	methods: {
		getQueryString,
		// 生成一个不会重复的 sessionkey
    generateSessionKey(length) {
      let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let key = '';
      for (let i = 0; i < length; i++) {
        key += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return key;
    },
		// 确认登录
		login() {
			const token = uni.getStorageSync('AccessToken') || ''
			this.token = token
      if (!token) {
				// #ifdef H5
				// H5端
				window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${this.redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
				// #endif

				// #ifdef MP-WEIXIN
				// 微信小程序端
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function (event) {
						const {
							code
						} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						uni.request({
							url: '', //仅为示例，并非真实接口地址。
							data: {
								code: event.code
							},
							success: (res) => {
								//获得token完成登录
								setTimeout(() => {
									uni.setStorageSync('AccessToken', res.token)
									uni.reLaunch({
										url: '/pages/index/index'
									})
								}, 500)
							}
						});
					},
					fail: function (err) {
						// 登录授权失败
						// err.code是错误码
					}
				})
				// #endif
			} else {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}
		},
		async getToken(code, sessionKey) {
      try {
        // 获取用户信息
        const res = await login({
          code, sessionKey
        })
        uni.setStorageSync("AccessToken", res.data);
				await this.getuserInfo();
				this.$nextTick(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				})
      } catch (err) {
				console.log(err);
			}
    },
		async getuserInfo() {
			const res = await getInfo();
			uni.setStorageSync('userInfo', JSON.stringify(res.user))
		}
	}
};
</script>
<style lang="scss" scoped>
@import 'index.scss';
</style>
